import axios, { AxiosInstance, AxiosRequestConfig, AxiosStatic } from 'axios';
class AxiosUtils{

    private request: AxiosInstance;
    private white: string[] = ["/user/login"];
    constructor(axios: AxiosStatic){
        this.request = axios.create({
            timeout: 5000,
            baseURL: "http://localhost:3001/devapi"
        })
    }

    requestInterceptors(request: AxiosInstance): any{
        request.interceptors.request.use(
            (confirm: AxiosRequestConfig<any>) => {
                
                const path:any = confirm.url
                if(this.white.indexOf(path)!== -1){
                    console.log(`我在白名单里: ${this.white}`)

                }else{
                    const token = localStorage.getItem('token');
                    if (token) {
                        // 在请求头中添加Authorization字段，并设置其值为获取到的token
                        confirm.headers = {
                           ...confirm.headers,
                            "Authorization": token
                        };
                    }
                    console.log(`我不在白名单里: ${this.white}`);
                }
                return confirm
            },
            (error:string) => {
                console.log('我是请求拦截器, 发送请求失败');
                return Promise.reject(error)
            }
         )
    }

    responseInterceptors(request: AxiosInstance): any{
        request.interceptors.response.use(
            (response: any) => {
                console.log('我是响应拦截器， 响应数据返回成功');
                return response
            },
            (error: string) =>{
                console.log('我是响应拦截器，响应数据返回失败');
                return Promise.reject(error)
            }
        )
    }

    getRequest(){
        this.requestInterceptors(this.request);
        this.responseInterceptors(this.request)
        return this.request
    }
}

export default new AxiosUtils(axios).getRequest();